package com.qf.controller.wxpay;

import cn.hutool.core.util.RandomUtil;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.qf.common.Constant;
import com.qf.config.MyWXPayConfig;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>@user HopeULife</p>
 * <p>@date 2021/11/1</p>
 */
@RestController
@RequestMapping("/wx")
@CrossOrigin("*")
public class WXPayController {

    //测试订单号
    private final static String HEADER = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    private final Log logger = LogFactory.getLog(WXPayController.class);
    private MyWXPayConfig myWXPayConfig;

    public WXPayController(MyWXPayConfig myWXPayConfig) {
        this.myWXPayConfig = myWXPayConfig;
    }

    @PostMapping("/to-pay")
    @ApiOperation("微信支付--开始支付")
    public Map<String, String> toPay() {
        String orderId = HEADER + RandomUtil.randomNumbers(5);
        WXPay wxPay = new WXPay(myWXPayConfig);
        Map<String, String> data = new HashMap<>();
        data.put(Constant.BODY, "测试数据");
        data.put(Constant.OUT_TRADE_NO, orderId);
        data.put(Constant.FEE_TYPE, "CNY");
        data.put(Constant.TOTAL_FEE, "1");
        data.put(Constant.TRADE_TYPE, "NATIVE");
        data.put(Constant.NOTIFY_URL, Constant.NEG_URL + "/wx/roll-back");
        try {
            Map<String, String> resp = wxPay.unifiedOrder(data);
            logger.info(resp);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 支付成功后回调路径
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/roll-back")
    @ApiOperation("微信支付--支付回调")
    public String paySuccess(HttpServletRequest request) throws Exception {
        ServletInputStream in = request.getInputStream();
        byte[] bs = new byte[1024];
        int len = -1;
        StringBuilder builder = new StringBuilder();
        while ((len = in.read(bs)) != -1) {
            builder.append(new String(bs, 0, len));
        }
        String s = builder.toString();
        Map<String, String> returnData = WXPayUtil.xmlToMap(s);
        logger.info(returnData);
        if (returnData != null && "success".equalsIgnoreCase(returnData.get(Constant.RETURN_CODE))) {
            Map<String, String> resp = new HashMap<>();
            resp.put(Constant.RETURN_CODE, "success");
            resp.put(Constant.RETURN_MSG, "OK");
            resp.put(Constant.APPID, "appid");
            resp.put(Constant.RESULT_CODE, "success");
            return WXPayUtil.mapToXml(resp);
        } else {
            logger.info("能走到这儿里说明支付失败了");
        }
        return null;
    }
}
